package com.ncmmall.mall.controller.business.supplier;

import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.attribute.GoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttribute;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * @Description: 商品审核管理
 * @Date: 2019-07-10 17:44
 */
@Controller
@RequestMapping(value = "/mall/supplier/goods/check")
public class SupplierGoodsCheckController {

    private final static Logger logger = LoggerFactory.getLogger(SupplierGoodsCheckController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsApplication goodsApplication;

    @Autowired
    private OperationLogApplication logApplication;


    @Value("${web.domain}")
    private String webDomain;

    /**
     * 审核商品列表
     *
     * @param model
     * @param pageParams
     * @param goods
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, Goods goods) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from Goods u where u.isSupplier=1  ", params, goods);
        QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);
        List<WebUser> merchants = queryChannelService.findAll(QWebUser.webUser.role.name.eq("MERCHANT"), WebUser.class);

        model.addAttribute("page", page).addAttribute("params", goods).addAttribute("merchants", merchants);

        return "mall/supplier/goods/check/list";
    }

    /**
     * 审核页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/check", method = RequestMethod.GET)
    private String check(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        List<GoodsAttribute> attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(goods.getMerchant().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()), GoodsAttribute.class);

        model.addAttribute("goods", goods).addAttribute("_method", "PUT").addAttribute("attributes", attributes);

        return "mall/supplier/goods/check/check";
    }

    /**
     * 审核商品
     *
     * @param requestWith
     * @param goods
     * @return
     */
    @RequestMapping(value = "/{id}/check", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> check(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Goods goods) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }
            goodsApplication.check(goods);
            logApplication.eventOfSystem(Securitys.currentUser(), "审核商品", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            logger.error("[审核商品异常]", e);
            return ImmutableMap.of("status", false, "message", "审核异常");
        }
    }

    /**
     * 批量审核通过
     *
     * @param requestWith
     * @param data
     * @return
     */
    @RequestMapping(value = "/allPass", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> allPass(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            goodsApplication.allPass(Lists.transform(ids, new Function<String, Goods>() {
                @Nullable
                @Override
                public Goods apply(@Nullable String input) {
                    Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Longs.tryParse(input)), Goods.class);
                    return goods;
                }
            }));

            logApplication.eventOfSystem(Securitys.currentUser(), "批量审核通过商品", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[批量审核通过商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }


    /**
     * 批量不通过审核
     *
     * @param requestWith
     * @param data
     * @return
     */
    @RequestMapping(value = "/allNotPass", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> allNotPass(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            goodsApplication.allNotPass(Lists.transform(ids, new Function<String, Goods>() {
                @Nullable
                @Override
                public Goods apply(@Nullable String input) {
                    Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Longs.tryParse(input)), Goods.class);
                    return goods;
                }
            }), "审核不通过");

            logApplication.eventOfSystem(Securitys.currentUser(), "批量审核不通过商品", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[批量审核不通过商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Goods goods) {

        if (goods.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", goods.getStatus());
        } else {
            sql += " and u.status in (2,3,4) ";
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo like :goodsno ";
            params.put("goodsno", "%" + goods.getGoodsNo() + "%");
        }

        if (goods.getMerchant() != null && goods.getMerchant().getId() > 0) {
            sql += " and u.merchant.id = :merchantId ";
            params.put("merchantId", goods.getMerchant().getId());
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", goods.getName());
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.defaultPrice " + goods.getOrderByPrice();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.store " + goods.getOrderByStore();
        } else if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        } else {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }

}
